<template>
<el-dialog
    class="edit-website"
    title="编辑网站" 
    :visible.sync="show"
    @click.stop 
    append-to-body
    top="50px"
    width="650px">
    <div class="container">
        <el-form :model="form" ref="form" label-width="60px">
            <el-form-item>
                <el-button 
                    type="primary" 
                    plain
                    @click="pasteData">
                    模板数据粘贴
                </el-button>
            </el-form-item>
            <el-form-item
                label-width="90px"
                label="所属分类" prop="type"
                :rules="[
                    { required: true, message: '不能为空'},
                    { min: 1, max: 30, message: '长度1-30', trigger: 'blur' },
                ]">
                <TypeSelectInput
                    v-model="form.type">
                </TypeSelectInput>
            </el-form-item>
            <el-form-item
                label-width="90px"
                label="名称" prop="name"
                :rules="[
                    { required: true, message: '不能为空'},
                    { min: 1, max: 100, message: '长度1-100', trigger: 'blur' },
                ]">
                <el-input 
                    v-model="form.name" 
                    clearable 
                    :disabled="!isDefined()">
                </el-input>
            </el-form-item>
            <el-form-item
                label-width="90px"
                label="网址" prop="link"
                :rules="[
                    { required: true, message: '不能为空'},
                    { min: 1, max: 300, message: '长度1-300', trigger: 'blur' }
                ]">
                <el-input 
                    :disabled="!isDefined()"
                    v-model="form.link" clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                label-width="90px"
                label="搜索" prop="search"
                :rules="[
                    { min: 0, max: 300, message: '长度1-300', trigger: 'blur' }
                ]">
                <el-input
                    :disabled="!isDefined()"
                    v-model="form.search" clearable>
                </el-input>
            </el-form-item>
            <el-form-item 
                v-show="isDefined()"
                label="icon" prop="icon"
                label-width="90px">
                <IconSelect
                    ref="IconSelect">
                </IconSelect>
            </el-form-item>
            <el-form-item
                v-if="oldData.website && oldData.website.iconfile"
                style="opacity: 0.5;"
                label-width="0px"
                label=" ">
                <div style="font-size: 12px;line-height: 1.5;margin-bottom: 5px;">
                    所传文件：指的是该网址上传过的icon文件。上传后会icon默认使用该文件的链接。该文件链接可以在其他地方使用。
                    该网址icon修改为其他链接时不影响该文件，当重新上传文件时会删除之前的文件，该网址被删除时也会删除该文件。
                </div>
                <div style="font-size: 12px;line-height: 1.5;">
                    {{'文件名：'+oldData.website.iconfile+"   文件链接：https://file.dumogu.top/"+oldData.website.iconfile}}
                </div>
            </el-form-item>
        </el-form>
    </div>
    <div slot="footer">
        <el-button type="primary" @click="updateData" :loading="loading">确定</el-button>
        <el-button type="danger" @click="resetForm">重置</el-button>
        <el-button @click="show=false" type="danger" plain>取消</el-button>
    </div>
</el-dialog>
</template>

<script>
/*
 编辑网站
 */
import {throttleFn} from '@/common/DebounceAndThrottle';
import IconSelect from "@/components/IconSelect";
import TypeSelectInput from"@/components/TypeSelectInput";
export default {
    name:"EditWebsite",
    components:{IconSelect,TypeSelectInput},
    data() {
        this.oldData = {};  //原始的数据
        return {
            loading:false,
            show:false,  //控制对话框的显示
            form: {
                id:0,
                name: '',
                link: '',
                icon: '',
                type:'',
                search:'',
                icon_:undefined,  //选择的icon文件
            },
        };
    },
    computed:{
        websiteTemplate(){  //全部网址模板
            return this.$store.state.public.websiteTemplate;
        },
    },
    methods: {
        pasteData(){  //粘贴模板数据
            let data = this.websiteTemplate;
            for(let index in this.data){
                if(data[index]){
                    this.form[index] = data[index];
                }
            }
            this.$refs.IconSelect.initData({
                activeIndex:0,
                websiteLink:this.form.link || '',
                activeImgUrl:this.form.icon || '',
            });//写入初始数据
        },
        isDefined(){  //是自定义网址
            return !this.oldData.website || this.oldData.website.defined;
        },
        initData({show=true,userWebsite={}}={}){  //写入初始化数据（可外部调用）
            userWebsite = JSON.parse(JSON.stringify(userWebsite));
            if (userWebsite.id) {
                this.form.id = userWebsite.id;
                this.form.type = userWebsite.type;
                this.form.name = userWebsite.website.name;
                this.form.link = userWebsite.website.link;
                this.form.icon = userWebsite.website.icon || '';
                this.form.search = userWebsite.website.search || '';
                this.oldData = userWebsite;
            }else{
                this.form = {};
                this.oldData = {};
            };
            this.show = show;
            this.$nextTick(()=>{   //防止组件还未加载完成
                this.$refs.IconSelect.initData({
                    activeIndex:0,
                    websiteLink:this.form.link || '',
                    activeImgUrl:this.form.icon || '',
                });//写入初始数据
            });
        },
        updateData:throttleFn(function(){//修改一个自定义网站
            this.form.name = this.form.name.trim();
            this.form.link = this.form.link.trim();
            this.form.type = this.form.type.trim();
            let iconData = this.$refs.IconSelect.getData();
            switch(iconData.activeIndex){
                case 0:
                    this.form.icon = iconData.activeImgUrl;
                    break;
                case 1:
                    this.form.icon_ = iconData.imgFile;
                    break;
            }
            this.$refs.form.validate((valid) => {
                if (!valid) return;
                if (this.loading) return;
                this.loading = true;
                let task;
                if(this.form.id){  //表示修改
                    task = this.$store.dispatch(
                        'user/updateUserWebsite',
                        {
                            ...this.form,
                        },
                    );
                }else{  //表示添加
                    task = this.$store.dispatch(
                        'user/addUserWebsite',
                        {
                            ...this.form,
                        },
                    );
                }
                task.then(()=>{
                    this.$message({
                        message:'成功！',
                        offset:55,
                        type:'success',
                    });
                    this.show = false;
                }).catch((msg) =>{
                    this.$message({
                        message:msg,
                        offset:55,
                        type:'error',
                    });
                }).finally(()=>{
                    this.loading = false;
                });
            });
        },700),
        resetForm() { //重置表单
            this.$refs.form.resetFields();
            this.$refs.IconSelect.initData({
                activeIndex:0,
                websiteLink:this.form.link || '',
                activeImgUrl:this.form.icon || '',
            });//写入初始数据
            this.initData({
                show:true,
                userWebsite:this.oldData,
            });  //写入最初传入的数据
        },
    },
};
</script>
<style lang="scss" scoped>
.edit-website{
    .container{
        width: 100%;
    }
    /deep/button{
        padding: 10px 15px;
    }
}
</style>